package org.example.java.util.concurrency.data_structure;

import java.util.Random;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by Juntao.Zhang on 2014/11/16.
 */
public class SynchronousQueueTest {
  public static void main(String[] args) {
    SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>(true);
    new Customer(queue, "C1").start();
    new Product(queue, "P1").start();
    new Product(queue, "P2").start();
    new Product(queue, "P3").start();
    new Product(queue, "P4").start();
    new Product(queue, "P5").start();
  }

  static class Product extends Thread {
    SynchronousQueue<Integer> queue;

    public Product(SynchronousQueue<Integer> queue, String name) {
      this.queue = queue;
      this.setName(name);
    }

    @Override
    public void run() {
      while (true) {
        int rand = new Random().nextInt(1000);
        System.out.println(Thread.currentThread().getName() + " 生产了一个产品：" + rand);
        System.out.println(Thread.currentThread().getName() + " 等待运送出去...");
        try {
          TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        try {
          queue.put(rand);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 等待运送 " + rand + " 成功");
      }
    }
  }

  static class Customer extends Thread {
    SynchronousQueue<Integer> queue;

    public Customer(SynchronousQueue<Integer> queue, String name) {
      this.queue = queue;
      this.setName(name);
    }

    @Override
    public void run() {
      while (true) {
        try {
          try {
            TimeUnit.MILLISECONDS.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " 消费了一个产品:" + queue.take());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
